﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BestTrader.Cms.Models;
using BestTrader.Cms.IRepository;
using System.Text;
using BestTrader.Cms.Admin.Validation;
using FluentValidation.Results;
using BestTrader.Cms.ViewModels;
using BestTrader.Cms.Core.Helper;
using BestTrader.Cms.IServices;
using BestTrader.Cms.Core;
using System.Security.Claims;
using BestTrader.Cms.Admin.Filter;
using Microsoft.AspNetCore.Authorization;

namespace BestTrader.Cms.Admin.Controllers
{
    [Authorize]
    public class ManagerController : BaseController
    {
        public String UserId { get { return User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value; } }
        public String RoleId { get { return User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role)?.Value; } }

        private readonly IManagerService _service;
        private readonly IManagerDataService _dataService;
        private readonly IManagerRoleService _roleService;
        private readonly IQiniuService _qiniuService;
        private readonly IManagerTokenService _tokenService;
        private readonly IManagerRoleService _managerRoleService;
        private readonly IDESEncryptService _desService;

        public ManagerController(
            IManagerService service
           ,IManagerDataService dataService
           ,IManagerRoleService roleService
           ,IQiniuService qiniuService
           ,IManagerTokenService tokenService
           , IManagerRoleService managerRoleService
           , IDESEncryptService desService
            )
        {
            _service = service;
            _dataService = dataService;
            _roleService = roleService;
            _qiniuService = qiniuService;
            _tokenService = tokenService;
            _managerRoleService = managerRoleService;
            _desService = desService;
        }

        public IActionResult Index() => View();


        public string LoadData([FromQuery]ManagerRequestModel model)
        {
            return JsonHelper.ObjectToJSON(_service.LoadData(model, UserId, RoleId));
        }

        [HttpGet]
        public IActionResult AddOrModify()
        {
            var roleList = _roleService.GetListByCondition(new ManagerRoleRequestModel
            {
                Key = null
            });
            return View(roleList);
        }

        [HttpGet]
        public IActionResult ModifyData()
        {
            ViewData["QiniuToken"] = _qiniuService.GetToken();
            var roleList = _roleService.GetListByCondition(new ManagerRoleRequestModel
            {
                Key = null
            });
            ViewData["IsState"] = _service.GetManagerStateByManagerId(UserId);
            var manager = _service.GetManagerTableById(UserId);
            var AgentUserId = manager.Data?.AddManagerId.ToString();
            
           ViewData["IsHideCheckPhone"] = _service.CheckSpecialAgentIsHiddenPhoneByUID(DESEncryptHelper.Encrypt(AgentUserId));

            return View(roleList);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public string ModifyData([FromForm]ManagerModifyDataModel item)
        {
            var result = new BaseResult();
            ManagerDataValidation validationRules = new ManagerDataValidation();
            ValidationResult results = validationRules.Validate(item);
            if (results.IsValid)
            {
                result = _dataService.ModifyData(item, UserId);
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return JsonHelper.ObjectToJSON(result);
        }

        [HttpGet]
        public string GetCurrentUserInfo()
        {
            var user = _service.GetManagerById(UserId);

            return JsonHelper.ObjectToJSON(user);
        }


        [HttpGet]
        public IActionResult Preview()
        {
            var roleList = _roleService.GetListByCondition(new ManagerRoleRequestModel
            {
                Key = null
            });
            return View(roleList);
        }

        [HttpGet]
        public string DecryptManagerInfo(int managerId)
        {
            var result = _service.DecryptManagerInfoById(managerId);
            return JsonHelper.ObjectToJSON(result);
        }



        [HttpPost, ValidateAntiForgeryToken]
        public string AddOrModify([FromForm]ManagerAddOrModifyModel item)
        {
            var result = new BaseResult();
            ManagerValidation validationRules = new ManagerValidation();
            ValidationResult results = validationRules.Validate(item);
            if (results.IsValid)
            {
                result = _service.AddOrModify(item, UserId);
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return JsonHelper.ObjectToJSON(result);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public string Delete(int[] roleId)
        {
            return JsonHelper.ObjectToJSON(_service.DeleteIds(roleId));
        }

        [HttpPost, ValidateAntiForgeryToken]
        public string ResetPassword(int managerId)
        {
            return JsonHelper.ObjectToJSON(_service.ResetPassword(managerId, UserId));
        }

        [HttpPost, ValidateAntiForgeryToken]
        public string MyCode()
        {
            var _userId = _managerRoleService.CheckIsAdministrator(UserId);

            var result = new BaseResult()
            {
                ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode,
                ResultMsg = AESEncryptHelper.Encode(_userId, CzarCmsKeys.AesEncryptKeys)
            };
            
            return JsonHelper.ObjectToJSON(result);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public string ChangeLockStatus([FromForm]ChangeStatusModel item)
        {
            var result = new BaseResult();
            ManagerLockStatusModelValidation validationRules = new ManagerLockStatusModelValidation();
            ValidationResult results = validationRules.Validate(item);
            if (results.IsValid)
            {
                result = _service.ChangeLockStatus(item);
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return JsonHelper.ObjectToJSON(result);
        }

        #region 审核
        [HttpPost, ValidateAntiForgeryToken]
        public string Audit ([FromForm]ManagerAuditRegisterModel item)
        {
            var result = _service.AuditRegister(item);

            return JsonHelper.ObjectToJSON(result);
        }

        #endregion

        #region 添加驳回原因
        [HttpPost, ValidateAntiForgeryToken]
        public string AuditRejectRemark(int managerId,string auditRemark)
        {
            var result = _service.AddAuditRemark(managerId, auditRemark);
            return JsonHelper.ObjectToJSON(result);

        }
        #endregion
        [HttpGet]
        public IActionResult Structure()
        {

            return View();
        }

        [HttpGet]
        public string GetStructureTree()
        {
            var result = _service.GetCacheAllManager(UserId, RoleId);
            return JsonHelper.ObjectToJSON(result);
        }
        /// <summary>
        /// 获取重置链接
        /// </summary>
        /// <param name="managerId"></param>
        /// <returns></returns>
        [HttpPost, ValidateAntiForgeryToken]
        public string ResetPushLink([FromForm] string managerId)
        {
            var result = new TableDataResult<String>();
            var pushUrl = "";

            var managerData =_service.GetManagerTableById(managerId);
            
            if (managerData.Data != null )
            {
                var manager = managerData.Data;
                var RoleId = 0;
                var UserId = 0;
                var parentManager = _service.GetManagerTableById(manager.AddManagerId.ToString());
                if (parentManager.Data != null)
                {
                    UserId = parentManager.Data.Id;
                    RoleId = parentManager.Data.RoleId;

                    var tokenEntity = _tokenService.AddOrModify(UserId);

                    if (RoleId >= 3)
                        pushUrl = $"{ Request.Scheme }://{ Request.Host.Value }/Account/TerminalQuestionnaire?UID={ DESEncryptHelper.Encrypt($"{ UserId }") }&Reg={ tokenEntity.Data }";

                   
                    int[] delUserId = { manager.Id};
                    ///删除这个用户
                    _service.DeleteIds(delUserId);

                    result.Data = pushUrl;
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
                else {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }

            }
            else {
                result.ResultCode = ResultCodeAddMsgKeys.CommonFailNoDataCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonFailNoDataMsg;
            }

            return JsonHelper.ObjectToJSON(result);
        }


    }
}